package com.ninong.ker.admin.sevice.impl;

import java.util.Arrays;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ninong.ker.admin.service.dto.DicDetailDTO;
import com.ninong.ker.common.auth.SecurityAdmin;
import com.ninong.ker.common.tools.PropertyUtil;
import com.ninong.ker.common.user.OnlineUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ninong.ker.admin.domain.DicDetail;
import com.ninong.ker.admin.mapper.DicDetailMapper;
import com.ninong.ker.admin.sevice.DicDetailService;
import com.ninong.ker.common.exception.CmdException;
import com.ninong.ker.common.tools.Constants;

/**
 * 
 * @author cmd
 *
 */
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class DicDetailServiceImpl extends ServiceImpl<DicDetailMapper, DicDetail> implements DicDetailService {

	@Autowired
	private SecurityAdmin securityAdmin;
	@Override
	public List<DicDetail> listPage(DicDetailDTO dto) {
		OnlineUser onlineUser = securityAdmin.currentUser();
		String tenantId = onlineUser.getTenantId();
		LambdaQueryWrapper<DicDetail> query = new LambdaQueryWrapper<>();
		query.eq(DicDetail::getDicId, dto.getDicId());
		query.eq(DicDetail::getTenantId, tenantId);
		return baseMapper.selectList(query);
	}

	@Override
	public void delete(String[] ids) {
		baseMapper.deleteBatchIds(Arrays.asList(ids));
	}

	@Override
	public void create(DicDetail entity) {
		OnlineUser onlineUser = securityAdmin.currentUser();
		String tenantId = onlineUser.getTenantId();
		Long count;
		if (StringUtils.isEmpty(entity.getId())) {
			count = baseMapper.selectCount(
					new LambdaQueryWrapper<DicDetail>().eq(DicDetail::getDicId, entity.getDicId()).eq(DicDetail::getCode, entity.getCode()));
			if (count > Constants.ZERO) {
				String mess = PropertyUtil.getProperty("DIC_CODE_REPEAT");
				throw new CmdException(100,mess);
			}
		} else {
			count = baseMapper.selectCount(new LambdaQueryWrapper<DicDetail>().ne(DicDetail::getId, entity.getId())
					.eq(DicDetail::getDicId, entity.getDicId()).eq(DicDetail::getCode, entity.getCode()));
			if (count > Constants.ZERO) {
				String mess = PropertyUtil.getProperty("DIC_CODE_REPEAT");
				throw new CmdException(100,mess);
			}

		}
		entity.setTenantId(tenantId);
		saveOrUpdate(entity);
	}

	@Override
	public DicDetail get(String id) {
		DicDetail entity = baseMapper.selectById(id);
		if (ObjectUtils.isEmpty(entity)) {
			entity = new DicDetail();
		}
		return entity;
	}

}
